package com.lisp.algorithm.test.sort;

import java.util.Arrays;

public class ArrayAdd {

	public static void main(String[] args) {
		int a[] = {9, 9, 9};
		int b[] = {1, 0};
		int[] sum = arrayAdd(a, b);
		System.out.println(Arrays.toString(sum));
	}
	
	private static int[] arrayAdd(int a[], int b[]) {
		int maxLength = Math.max(a.length, b.length);
		int ret[] = new int[maxLength + 1];
		
		boolean carry = false;
		for(int i=0; i<ret.length; i++) {
			int sum = readLast(a, i) + readLast(b, i);
			
			if(carry) {
				sum = sum + 1;
				carry = false;
			}
			
			if(sum >= 10) {
				carry = true;
				setLast(ret, i, sum-10);
			} else {
				setLast(ret, i, sum);
			}
		}
		
		return ret;
	}
	
	private static int readLast(int a[], int i) {
		if(i >= a.length) {
			return 0;
		} else {
			return a[a.length - i - 1];
		}
	}
	
	private static void setLast(int a[], int i, int val) {
		a[a.length - i - 1] = val;
	}
}
